package com.business.web.spring;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.business.domain.T_contract_bill;
import com.business.service.T_contract_billService;
import com.common.utils.DateUtil;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.business.domain.T_task_node_instance;
import com.easyworkflow.web.spring.WorkFlowController;

//import com.workflow.WorkFlowUtils;
import com.common.db.JsonVO;
import com.common.db.Pg;
import com.common.utils.BeanUtils;
import com.business.domain.T_contract;
//import com.business.mapper.T_contractMapper;
import com.business.service.T_contractService;

@Controller
@RequestMapping("/t_contract")

public class T_contractController extends WorkFlowController {

    private static Logger log = Logger.getLogger(T_contractController.class.getName());

    @Resource
    private T_contractService t_contractService;
    @Resource
    private T_contract_billService t_contract_billService;

    //@Autowired
    //private WorkFlowUtils workFlowUtils;

    //@Resource
    //private T_contractMapper mapper;
    //private int id;
    //private int[] ids;
    private Pg pg;

    /**
     * 1、获取 T_contract信息列表，并且在列表页面展示
     *
     * @param request
     * @return Pg，json格式
     */
    @RequestMapping("/getAllT_contract")
    @ResponseBody
    public Pg getAllT_contract(HttpServletRequest request) {
        int pageSize = 10;
        int startIndex = 0;
        T_contract t_contract = new T_contract();
        try {
            if (request.getParameter("pageSize") != null) {
                pageSize = BeanUtils.stringToInt("pageSizeFlag", request.getParameter("pageSize"));
            }
            if (request.getParameter("startIndex") != null) {
                startIndex = BeanUtils.stringToInt("startIndexFlag", request.getParameter("startIndex"));
            }
            if (request.getParameter("process_code") != null) { //取得动作流 流程英文名称，后台查询数据关联使用
                t_contract.setProcess_code(request.getParameter("process_code"));
            }
            if (request.getParameter("contractno") != null && !"".equals(request.getParameter("contractno"))) {
                t_contract.setContractno(request.getParameter("contractno"));
            }
            if (request.getParameter("conpanyname") != null && !"".equals(request.getParameter("conpanyname"))) {
                t_contract.setConpanyname(request.getParameter("conpanyname"));
            }
            if (request.getParameter("buildingname") != null && !"".equals(request.getParameter("buildingname"))) {
                t_contract.setBuildingname(request.getParameter("buildingname"));
            }
            if (request.getParameter("housename") != null && !"".equals(request.getParameter("housename"))) {
                t_contract.setHousename(request.getParameter("housename"));
            }
            if (request.getParameter("area") != null && !"".equals(request.getParameter("area"))) {
                t_contract.setArea(request.getParameter("area"));
            }
            if (request.getParameter("buildingtype") != null && !"".equals(request.getParameter("buildingtype"))) {
                t_contract.setBuildingtype(request.getParameter("buildingtype"));
            }
            if (request.getParameter("biztype") != null && !"".equals(request.getParameter("biztype"))) {
                t_contract.setBiztype(request.getParameter("biztype"));
            }
            if (request.getParameter("checkstatu") != null && !"".equals(request.getParameter("checkstatu"))) {
                t_contract.setCheckstatu(request.getParameter("checkstatu"));
            }
            if (request.getParameter("status") != null && !"".equals(request.getParameter("status"))) {
                t_contract.setStatus(request.getParameter("status"));
            }
            if (request.getParameter("contracttype") != null && !"".equals(request.getParameter("contracttype"))) {
                t_contract.setContracttype(request.getParameter("contracttype"));
            }
            if (request.getParameter("linkman") != null && !"".equals(request.getParameter("linkman"))) {
                t_contract.setLinkman(request.getParameter("linkman"));
            }
            if (request.getParameter("info") != null && !"".equals(request.getParameter("info"))) {
                t_contract.setInfo(request.getParameter("info"));
            }
            if (request.getParameter("companytel") != null && !"".equals(request.getParameter("companytel"))) {
                t_contract.setCompanytel(request.getParameter("companytel"));
            }
            if (request.getParameter("signer") != null && !"".equals(request.getParameter("signer"))) {
                t_contract.setSigner(request.getParameter("signer"));
            }
            if (request.getParameter("businesstype") != null && !"".equals(request.getParameter("businesstype"))) {
                t_contract.setBusinesstype(request.getParameter("businesstype"));
            }
            if (request.getParameter("attachpath") != null && !"".equals(request.getParameter("attachpath"))) {
                t_contract.setAttachpath(request.getParameter("attachpath"));
            }
            if (request.getParameter("signtime") != null && !"".equals(request.getParameter("signtime"))) {
                t_contract.setSigntime(request.getParameter("signtime"));
            }
            if (request.getParameter("paytype") != null && !"".equals(request.getParameter("paytype"))) {
                t_contract.setPaytype(request.getParameter("paytype"));
            }
            if (request.getParameter("payday") != null && !"".equals(request.getParameter("payday"))) {
                t_contract.setPayday(request.getParameter("payday"));
            }
            if (request.getParameter("creater") != null && !"".equals(request.getParameter("creater"))) {
                t_contract.setCreater(request.getParameter("creater"));
            }
            if (request.getParameter("creattime") != null && !"".equals(request.getParameter("creattime"))) {
                t_contract.setCreattime(request.getParameter("creattime"));
            }
            if (request.getParameter("updater") != null && !"".equals(request.getParameter("updater"))) {
                t_contract.setUpdater(request.getParameter("updater"));
            }
            if (request.getParameter("updatetime") != null && !"".equals(request.getParameter("updatetime"))) {
                t_contract.setUpdatetime(request.getParameter("updatetime"));
            }
            if (request.getParameter("ext1") != null && !"".equals(request.getParameter("ext1"))) {
                t_contract.setExt1(request.getParameter("ext1"));
            }
            if (request.getParameter("ext2") != null && !"".equals(request.getParameter("ext2"))) {
                t_contract.setExt2(request.getParameter("ext2"));
            }
            if (request.getParameter("ext3") != null && !"".equals(request.getParameter("ext3"))) {
                t_contract.setExt3(request.getParameter("ext3"));
            }
            if (request.getParameter("ext4") != null && !"".equals(request.getParameter("ext4"))) {
                t_contract.setExt4(request.getParameter("ext4"));
            }
            if (request.getParameter("ext5") != null && !"".equals(request.getParameter("ext5"))) {
                t_contract.setExt5(request.getParameter("ext5"));
            }
            if (request.getParameter("ext6") != null && !"".equals(request.getParameter("ext6"))) {
                t_contract.setExt6(request.getParameter("ext6"));
            }
            if (request.getParameter("ext7") != null && !"".equals(request.getParameter("ext7"))) {
                t_contract.setExt7(request.getParameter("ext7"));
            }
            if (request.getParameter("ext8") != null && !"".equals(request.getParameter("ext8"))) {
                t_contract.setExt8(request.getParameter("ext8"));
            }
            if (request.getParameter("ext9") != null && !"".equals(request.getParameter("ext9"))) {
                t_contract.setExt9(request.getParameter("ext9"));
            }
            if (request.getParameter("ext10") != null && !"".equals(request.getParameter("ext10"))) {
                t_contract.setExt10(request.getParameter("ext10"));
            }
            if (request.getParameter("ext11") != null && !"".equals(request.getParameter("ext11"))) {
                t_contract.setExt11(request.getParameter("ext11"));
            }
            if (request.getParameter("ext12") != null && !"".equals(request.getParameter("ext12"))) {
                t_contract.setExt12(request.getParameter("ext12"));
            }
            if (request.getParameter("billname") != null && !"".equals(request.getParameter("billname"))) {
                t_contract.setBillname(request.getParameter("billname"));
            }
            if (request.getParameter("billcompanyno") != null && !"".equals(request.getParameter("billcompanyno"))) {
                t_contract.setBillcompanyno(request.getParameter("billcompanyno"));
            }
            if (request.getParameter("yajin") != null && !"".equals(request.getParameter("yajin"))) {
                t_contract.setYajin(request.getParameter("yajin"));
            }
            if (request.getParameter("yajinscale") != null && !"".equals(request.getParameter("yajinscale"))) {
                t_contract.setYajinscale(request.getParameter("yajinscale"));
            }
            if (request.getParameter("contracttel") != null && !"".equals(request.getParameter("contracttel"))) {
                t_contract.setContracttel(request.getParameter("contracttel"));
            }
            if (request.getParameter("contractstartdate") != null && !"".equals(request.getParameter("contractstartdate"))) {
                t_contract.setContractstartdate(request.getParameter("contractstartdate"));
            }
            if (request.getParameter("contractenddate") != null && !"".equals(request.getParameter("contractenddate"))) {
                t_contract.setContractenddate(request.getParameter("contractenddate"));
            }
            if (request.getParameter("htyajinunit") != null && !"".equals(request.getParameter("htyajinunit"))) {
                t_contract.setHtyajinunit(request.getParameter("htyajinunit"));
            }
            if (request.getParameter("feiyongname") != null && !"".equals(request.getParameter("feiyongname"))) {
                t_contract.setFeiyongname(request.getParameter("feiyongname"));
            }
            if (request.getParameter("huowumingcheng") != null && !"".equals(request.getParameter("huowumingcheng"))) {
                t_contract.setHuowumingcheng(request.getParameter("huowumingcheng"));
            }
            if (request.getParameter("youhuizhengce") != null && !"".equals(request.getParameter("youhuizhengce"))) {
                t_contract.setYouhuizhengce(request.getParameter("youhuizhengce"));
            }
            if (request.getParameter("youhuizhengcename") != null && !"".equals(request.getParameter("youhuizhengcename"))) {
                t_contract.setYouhuizhengcename(request.getParameter("youhuizhengcename"));
            }
            if (request.getParameter("contractfeeunit") != null && !"".equals(request.getParameter("contractfeeunit"))) {
                t_contract.setContractfeeunit(request.getParameter("contractfeeunit"));
            }
            if (request.getParameter("contractnumunit") != null && !"".equals(request.getParameter("contractnumunit"))) {
                t_contract.setContractnumunit(request.getParameter("contractnumunit"));
            }
            if (request.getParameter("contractcounttype") != null && !"".equals(request.getParameter("contractcounttype"))) {
                t_contract.setContractcounttype(request.getParameter("contractcounttype"));
            }
            if (request.getParameter("contractpaytype") != null && !"".equals(request.getParameter("contractpaytype"))) {
                t_contract.setContractpaytype(request.getParameter("contractpaytype"));
            }
            if (request.getParameter("contractdatetype") != null && !"".equals(request.getParameter("contractdatetype"))) {
                t_contract.setContractdatetype(request.getParameter("contractdatetype"));
            }
            if (request.getParameter("energyfeeunit") != null && !"".equals(request.getParameter("energyfeeunit"))) {
                t_contract.setEnergyfeeunit(request.getParameter("energyfeeunit"));
            }
            if (request.getParameter("energytnumunit") != null && !"".equals(request.getParameter("energytnumunit"))) {
                t_contract.setEnergytnumunit(request.getParameter("energytnumunit"));
            }
            if (request.getParameter("energycounttype") != null && !"".equals(request.getParameter("energycounttype"))) {
                t_contract.setEnergycounttype(request.getParameter("energycounttype"));
            }
            if (request.getParameter("energypaytype") != null && !"".equals(request.getParameter("energypaytype"))) {
                t_contract.setEnergypaytype(request.getParameter("energypaytype"));
            }
            if (request.getParameter("energytdatetype") != null && !"".equals(request.getParameter("energytdatetype"))) {
                t_contract.setEnergytdatetype(request.getParameter("energytdatetype"));
            }
            if (request.getParameter("propertyfeeunit") != null && !"".equals(request.getParameter("propertyfeeunit"))) {
                t_contract.setPropertyfeeunit(request.getParameter("propertyfeeunit"));
            }
            if (request.getParameter("propertynumunit") != null && !"".equals(request.getParameter("propertynumunit"))) {
                t_contract.setPropertynumunit(request.getParameter("propertynumunit"));
            }
            if (request.getParameter("propertycounttype") != null && !"".equals(request.getParameter("propertycounttype"))) {
                t_contract.setPropertycounttype(request.getParameter("propertycounttype"));
            }
            if (request.getParameter("propertypaytype") != null && !"".equals(request.getParameter("propertypaytype"))) {
                t_contract.setPropertypaytype(request.getParameter("propertypaytype"));
            }
            if (request.getParameter("propertydatetype") != null && !"".equals(request.getParameter("propertydatetype"))) {
                t_contract.setPropertydatetype(request.getParameter("propertydatetype"));
            }
            if (request.getParameter("contractid") != null && !"".equals(request.getParameter("contractid"))) {
                t_contract.setContractid(new Integer(request.getParameter("contractid")));
            }

            if (request.getParameter("startdate") != null && !"".equals(request.getParameter("startdate"))) {
                t_contract.setStartdate(request.getParameter("startdate"));
            }
            if (request.getParameter("enddate") != null && !"".equals(request.getParameter("enddate"))) {
                t_contract.setEnddate(request.getParameter("enddate"));
            }
            t_contract.setStartNo(startIndex);
            t_contract.setPageSize(pageSize);
            t_contract.setEndNo(pageSize);
            List<T_contract> findAll = t_contractService.findAll(t_contract);
            int totalCount = t_contractService.findCountAll(t_contract);
            pg = new Pg(findAll, totalCount, pageSize, startIndex);
            request.setAttribute("t_contractList", findAll);
            request.setAttribute("pg", pg);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("------query t_contractList error:" + e);
        }

        return pg;
    }

    /**
     * 2、新增保存  T_contract信息并且返回成功或者失败信息json格式结果如：result:[success/error]
     *
     * @param t_contract
     * @param request
     * @return
     */
    @RequestMapping("/saveT_contract")
    @ResponseBody
    public JsonVO saveT_contract(T_contract t_contract, HttpServletRequest request, HttpServletResponse response) {
        JsonVO vo = new JsonVO();
        vo.setResult("error");
        vo.setJieguo(false);
        //如果有特殊需求，需要将json对象值转成java实体对象属性值
        if (t_contractService.save(t_contract) > 0) {
            vo.setResult("success");
            vo.setJieguo(true);
        }
        return vo;
    }

    /**
     * 3。1、修改T_contract信息并且返回成功或者失败信息json格式结果如：result:[success/error]
     *
     * @param t_contract
     * @param request
     * @return JsonVO
     */
    @RequestMapping("/updateT_contract")
    @ResponseBody
    public JsonVO updateT_contract(T_contract t_contract, HttpServletRequest request) {
        JsonVO vo = new JsonVO();
        vo.setResult("error");
        vo.setJieguo(false);
        //如果有特殊值需要处理，在此处手工转换
        //T_contract t_contractTemp = t_contractService.findById(t_contract);
        //t_contractTemp.setXXX(t_contract.getXXX());
        //if(t_contractService.update(t_contractTemp)){

        try {

            if (t_contractService.update(t_contract) > 0) {
                int billrowsnum = new Integer(request.getParameter("billrowsnum")).intValue();
                log.info("------需要生成账单数量billrowsnum=" + billrowsnum); //从1开始；
                int i = 0;

                String billstartdateName = "billstartdate";
                String billenddateName = "billenddate";
                String billareaName = "billarea";
                String billpaydateName = "billpaydate";
                String billfinalmoneName = "billfinalmone";

                while (i < billrowsnum) {
                    i++;
                    String billstartdate = "";
                    String billenddate = "";
                    String billarea = "";
                    String billpaydate = "";
                    String billfinalmone = "";
                    billstartdate = request.getParameter(billstartdateName + i);
                    billenddate = request.getParameter(billenddateName + i);
                    billarea = request.getParameter(billareaName + i);
                    billpaydate = request.getParameter(billpaydateName + i);
                    billfinalmone = request.getParameter(billfinalmoneName + i);
                    T_contract_bill tcb = new T_contract_bill();
                    tcb.setBillstartdate(billstartdate);
                    tcb.setBillenddate(billenddate);
                    tcb.setArea(billarea);
                    tcb.setPayday(billpaydate);
                    tcb.setTotalprice(new Double(billfinalmone));
                    t_contract_billService.save(tcb);
                }

                vo.setResult("success");
                vo.setJieguo(true);
            }
        } catch (Exception e) {
            vo.setResult("error");
            vo.setJieguo(false);
            vo.setInfo(e.getMessage());
            e.printStackTrace();
            log.error(e.toString());
        } finally {
            return vo;
        }

    }

    /**
     * 3。2、提交审核业务数据
     * 修改T_contract信息并且返回成功或者失败信息json格式结果如：result:[success/error]
     *
     * @param t_contract
     * @param request
     * @return JsonVO
     */
    @RequestMapping("/tjshT_contract")
    @ResponseBody
    public JsonVO tjshT_company(T_contract t_contract, HttpServletRequest request) {
        //启动工作流； 请假流程；
        return startMyTask(getTaskIdByBiztype(t_contract.getBiztype()), t_contract.getBiztype(), t_contract.getContractid(), request);
    }

    /**
     * 3.3、提交T_contract审核通过，并且返回成功或者失败信息json格式结果如：result:[success/error]
     *
     * @param t_task_node_instance
     * @param request
     * @return JsonVO
     */
    @RequestMapping("/shtgT_contract")
    @ResponseBody
    public JsonVO shtgT_contract(T_task_node_instance t_task_node_instance, HttpServletRequest request) {
        return doMyAgree(t_task_node_instance.getTninstanceid(), t_task_node_instance.getNote(), request);
    }

    /**
     * 3.4、提交T_contract审核退回，信息并且返回成功或者失败信息json格式结果如：result:[success/error]
     *
     * @param t_task_node_instance
     * @param request
     * @return JsonVO
     */
    @RequestMapping("/shthT_contract")
    @ResponseBody
    public JsonVO shthT_contract(T_task_node_instance t_task_node_instance, HttpServletRequest request) {
        return doMyBack(t_task_node_instance.getTninstanceid(), t_task_node_instance.getNote(), request);
    }

    /**
     * 4、根据id查询T_contract单个信息并显示在修改页面
     *
     * @param id
     * @param request
     * @return T_contract json格式字符串
     */
    @RequestMapping("/getT_contract")
    @ResponseBody
    public T_contract getT_contract(Integer id, HttpServletRequest request) {
        T_contract t_contract = new T_contract();
        t_contract.setContractid(id);
        return t_contractService.findById(t_contract);
    }

    /**
     * 5、删除T_contract根据id
     *
     * @param id
     * @param request
     * @param response return JsonVO ：json格式字符串
     */
    @RequestMapping("/delT_contract")
    @ResponseBody
    public JsonVO delT_contract(Integer id, HttpServletRequest request, HttpServletResponse response) {
        JsonVO vo = new JsonVO();
        vo.setResult("error");
        vo.setJieguo(false);

        T_contract t_contract = new T_contract();
        t_contract.setContractid(id);

        if (t_contractService.delete(t_contract) > 0) {
            vo.setResult("success");
            vo.setJieguo(true);
        }
        return vo;
    }

    /**
     * 5、2 生效 or作废 T_contract根据id 和状态；
     *
     * @param id
     * @param status   ：待生效、已生效、已作废；
     * @param request
     * @param response return JsonVO ：json格式字符串；
     */
    @RequestMapping("/effT_contract")
    @ResponseBody
    public JsonVO effT_contract(Integer id, String status, HttpServletRequest request, HttpServletResponse response) {
        JsonVO vo = new JsonVO();
        vo.setResult("error");
        vo.setJieguo(false);
        try {
            T_contract t_contract = new T_contract();
            t_contract.setContractid(id);
            t_contract = t_contractService.findById(t_contract);
            t_contract.setStatus(status);

            if (t_contractService.update(t_contract) > 0) {
                vo.setResult("success");
                vo.setJieguo(true);
                //更新为“已生效”时 要生成 物业费账单 or 租金账单； 物业费每天生成提醒预警，根据合同起始日后推按 设置周期 收费；
                // 能耗账单需要抄表数据录入或者接入后 生成（月底抄表）， 能耗费用 5号晚上批量生成；6号可以通知客户缴费；
                if (status.equals("已生效")) {
                    List billList = creatBillList(t_contract);
                    Iterator it = billList.iterator();
                    int i = 0;
                    while (null != it && it.hasNext()) {
                        i++;
                        T_contract_bill t_contract_bill;
                        t_contract_bill = (T_contract_bill) it.next();
                        t_contract_bill.setContractno(t_contract.getContractno());
                        t_contract_bill.setStatus("待生效");
                        t_contract_bill.setBillno(DateUtil.getCurrDateTime() + new Double(Math.random()).toString().substring(15));
                        t_contract_bill.setCreater(request.getSession().getAttribute("FREE_CURRENT_USER").toString());
                        t_contract_bill.setCreattime(DateUtil.getCurrDateTime());
                        t_contract_bill.setExt1(t_contract.getConpanyname()); //业主租客
                        t_contract_bill.setExt2(t_contract.getBuildingname()); //楼栋
                        t_contract_bill.setExt3(t_contract.getHousename()); //房号
                        t_contract_bill.setExt4(t_contract.getPayday()); //提前付款天数
                        t_contract_bill.setArea(t_contract.getArea());
                        t_contract_bill.setBasefee(t_contract.getPropertyprice());
                        String contracttype = t_contract.getContracttype();
                        String biztype = "";
                        String billtype = "";
                        if ("物业合同".equals(contracttype)) {
                            biztype = "wuye";
                            billtype = "物业费";
                        }
                        if ("租赁合同".equals(contracttype)) {
                            biztype = "zulin";
                            billtype = "租金";
                        }
                        t_contract_bill.setBiztype(biztype); //物业账单、租赁账单
                        t_contract_bill.setSftype("收款");
                        t_contract_bill.setBilltype(billtype);
                        t_contract_bill.setLinktel(t_contract.getCompanytel());

                        t_contract_billService.save(t_contract_bill);
                        log.info("------" + contracttype + "合同生效时，生成第" + i + "条" + billtype + "账单数据=" + t_contract_bill.toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return vo;
    }

    /**
     * 5、x 生效 or作废物业合同 T_contract根据id 和状态；
     *
     * @param id
     * @param status   ：待生效、已生效、已作废；
     * @param request
     * @param response return JsonVO ：json格式字符串；
     */
    @RequestMapping("/effWuyeT_contract")
    @ResponseBody
    public JsonVO effWuyeT_contract(Integer id, String status, HttpServletRequest request, HttpServletResponse response) {
        JsonVO vo = new JsonVO();
        vo.setResult("error");
        vo.setJieguo(false);
        try {
            T_contract t_contract = new T_contract();
            t_contract.setContractid(id);
            t_contract = t_contractService.findById(t_contract);
            t_contract.setStatus(status);

            if (t_contractService.update(t_contract) > 0) {
                vo.setResult("success");
                vo.setJieguo(true);
                //更新为“已生效”时 要生成 物业费账单 or 租金账单； 物业费每天生成提醒预警，根据合同起始日后推按 设置周期 收费；
                // 能耗账单需要抄表数据录入或者接入后 生成（月底抄表）， 能耗费用 5号晚上批量生成；6号可以通知客户缴费；
                if (status.equals("已生效")) {
                    List billList = creatBillList(t_contract);
                    Iterator it = billList.iterator();
                    int i = 0;
                    while (null != it && it.hasNext()) {
                        i++;
                        T_contract_bill t_contract_bill;
                        t_contract_bill = (T_contract_bill) it.next();
                        t_contract_bill.setContractno(t_contract.getContractno());
                        t_contract_bill.setStatus("待生效");
                        t_contract_bill.setBillno(DateUtil.getCurrDateTime() + new Double(Math.random()).toString().substring(15));
                        t_contract_bill.setCreater(request.getSession().getAttribute("FREE_CURRENT_USER").toString());
                        t_contract_bill.setCreattime(DateUtil.getCurrDateTime());
                        t_contract_bill.setExt1(t_contract.getConpanyname()); //业主租客
                        t_contract_bill.setExt2(t_contract.getBuildingname()); //楼栋
                        t_contract_bill.setExt3(t_contract.getHousename()); //房号
                        t_contract_bill.setExt4(t_contract.getPayday()); //提前付款天数
                        t_contract_bill.setArea(t_contract.getArea());
                        t_contract_bill.setBasefee(t_contract.getPropertyprice());
                        String contracttype = t_contract.getContracttype();
                        String biztype = "";
                        String billtype = "";
                        if ("物业合同".equals(contracttype)) {
                            biztype = "wuye";
                            billtype = "物业费";
                        }
                        if ("租赁合同".equals(contracttype)) {
                            biztype = "zulin";
                            billtype = "租金";
                        }
                        t_contract_bill.setBiztype(biztype); //物业账单、租赁账单
                        t_contract_bill.setSftype("收款");
                        t_contract_bill.setBilltype(billtype);
                        t_contract_bill.setLinktel(t_contract.getCompanytel());

                        t_contract_billService.save(t_contract_bill);
                        log.info("------" + contracttype + "合同生效时，生成第" + i + "条" + billtype + "账单数据=" + t_contract_bill.toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return vo;
    }

    /**
     * * 说明： 更新状态status="已生效"时，处理如下逻辑：
     * * 物业费账单规则如下：
     * * 1、生成账单期数； 目前默认规则：物业费先交后用，签订合同时，需要先交当前一个周期月物业费；
     * * 第一期应交费日期：= 合同签订日期 - 提前交费天数 为应交费日期；
     * * 2、生成每期账单明细； 期数、本期开始日期、结束日期、单价、面积、总价；
     * * 3、生成每期金额；每期金额 = 面积 * 单价 * 本周起天数；
     * * 4、生成应交费日期；
     * * 如果是第一个月，则： 应交费日期 = 合同开始日期 - 提前天数；
     * * 如果是非第一个月， 应交费日期 = 则是下期第一天（每月1号） - 提前天数；
     * 每个缴费周期： 从合同签订第一天到 下个月这一天前一天；
     *
     * @param t_contract
     * @return
     */
    private List creatBillList(T_contract t_contract) throws Exception {
        List list = new ArrayList();
        //（字符）合同开始日期
        String sstartdate = t_contract.getContractstartdate();
        //（字符）合同结束日期
        String senddate = t_contract.getContractenddate();
        //（日期型）合同开始日期
        Date startdate = DateUtil.parseByDefaultDatePattern(sstartdate); //yyyy-MM-dd,转成一个Date;
        //（日期型）合同结束日期
        Date enddate = DateUtil.parseByDefaultDatePattern(senddate); //yyyy-MM-dd,转成一个Date;
        //付款周期，月数，1、3、6、12个月付一次；
        int paytype = 1;
        String fkzq = t_contract.getPropertypaytype();  //付费频率，按x月付费；
        if ("按月".equals(fkzq)) {
            paytype = 1;
        } else if ("按季度".equals(fkzq)) {
            paytype = 3;
        } else if ("按半年".equals(fkzq)) {
            paytype = 6;
        } else if ("按年".equals(fkzq)) {
            paytype = 12;
        }
        //单价；
        Double propertyprice = t_contract.getPropertyprice();
        //提前付款天数；
        int propertyprepaydays = t_contract.getPropertyprepaydays();
        //默认 开始日期；
        Date currentStartdate = startdate; //DateUtil.addDay(DateUtil.addMonth(startdate, 1), -1);
        //默认 结束日期；
        Date currentEnddate = enddate;

        //如果第一天与 最后一天 比得到负数，说明还有下一期； 设置当前期 相关对象，设置完成后加入到list中；
        while (DateUtil.getDiffDate(currentStartdate, enddate) < 0) {  //firstMonthLastdDay - enddate；天数；
            T_contract_bill t_contract_bill = new T_contract_bill();
            //本期账单开始日期；
            t_contract_bill.setBillstartdate(DateUtil.format(currentStartdate, "yyyy-MM-dd"));
            log.info("------本期开始日期：" + DateUtil.format(currentStartdate, "yyyy-MM-dd") );

            //从本期开始日期加一个周期再减一天，即可能是本期最后一天；需要与合同结束日期比较；
            Date t1enddate = DateUtil.addDay(DateUtil.addMonth(currentStartdate, paytype), -1);

            int currentMonthDays = 0;
            Date fixCurrentStartdate  ;

            //如果加一个付款周期还是小于合同结束日期，则说明还有下一期；
            if (DateUtil.getDiffDate(t1enddate, enddate) < 0) {
                //本期账单结束日期；
                currentEnddate = t1enddate;
                t_contract_bill.setBillenddate(DateUtil.format(t1enddate, "yyyy-MM-dd"));
                //本期假如够一个付款周期，从开始日期加一个付款周期  与 合同结束日期比较；
                Date nextStartdate = DateUtil.addMonth(currentStartdate, paytype);
                log.info("------下期开始日期：" + DateUtil.format(nextStartdate, "yyyy-MM-dd") + ",本期结束日期：" + DateUtil.format(currentEnddate, "yyyy-MM-dd"));
                //tempstartdate = DateUtil.addMonth(tempstartdate, paytype);
                //计算本周期天数，用于计算本期物业、租赁费用；
                currentMonthDays = DateUtil.getDiffDate(currentEnddate, currentStartdate);
                fixCurrentStartdate = currentStartdate;
                // 设置下一期的开始日期，即需要再加一个付款周期；
                currentStartdate = nextStartdate;
                //DateUtil.addDay( new Date(DateUtil.format( t1enddate, "yyyy-MM-dd")), 1); //下一期的开始日期，即需要在上期结束日期再加一天；
            } else {
                //本期账单结束日期；说明到此结束了，本期不够一个月；
                t_contract_bill.setBillenddate(DateUtil.format(enddate, "yyyy-MM-dd"));
                currentEnddate = enddate;
                fixCurrentStartdate = currentStartdate;
                //计算本周期天数，用于计算本期物业、租赁费用；
                currentMonthDays = DateUtil.getDiffDate(enddate, currentStartdate);
                log.info("------最后一期,本期结束日期：" + DateUtil.format(enddate, "yyyy-MM-dd"));

                // 设置下一期条件 超过while 循环条件，以便while循环退出，不再执行生成下一期账单；
                currentStartdate = DateUtil.addMonth(currentStartdate, paytype);
            }

            t_contract_bill.setArea(t_contract.getArea());

            //根据不同合同类型，设置不同的金额计算方式；
            String contracttype = t_contract.getContracttype();
            if ("物业合同".equals(contracttype)) {
                //计算方式： 按照 当期天数*单价*面积 ；
                //t_contract_bill.setTotalprice(new Double(countTotalPrice(t_contract.getArea(), t_contract.getPropertyprice(), currentMonthDays))); //当期天数*单价*面积；

                //计算方式： 按照 每月物业费 * 每期月数 ；每月物业费为固定金额 ；
                t_contract_bill.setTotalprice( new Double( countTotalWuyePrice( t_contract.getPrice(), paytype))  ); //每月物业费 * 每期月数
                t_contract_bill.setMinprice(t_contract.getPrice()); //每期物业费金额
            }
            if ("租赁合同".equals(contracttype)) {
                //设置租金递增比例：rate，租金递增开始时间：feiyongname；
                Double rate = 1.00;
                String sfeiyongname = t_contract.getFeiyongname();
                //租金递增开始日期
                Date zujindizengdate = DateUtil.parseByDefaultDatePattern(sfeiyongname); //yyyy-MM-dd,转成一个Date;
                //本期开始日期
                Date benqistartdate = DateUtil.parseByDefaultDatePattern(t_contract_bill.getBillstartdate());
                //如果当前期的开始日期 > 租金开始递增日期；则租金递增系数 = rate（类似1.50），否则=1；
                if( DateUtil.getDiffDate( benqistartdate, zujindizengdate) >0 ){
                    rate = t_contract.getRate();
                }
                t_contract_bill.setExt5(rate.toString()); //租金递增系数；
                t_contract_bill.setExt6(sfeiyongname); //租金递增开始时间；
                //t_contract_bill.setTotalprice( new Double(countTotalZulinPrice( t_contract.getPrice(), paytype))  );
                //计算方式： 按照 每月租金 * 每期月数 * 递增系数;  // ；每月租金 = 每月租金/平方米 * 面积  ；
                t_contract_bill.setTotalprice( new Double( countTotalZulinPrice( t_contract.getPrice(), paytype, rate ))  ); //每月物业费 * 每期月数
                t_contract_bill.setMinprice(t_contract.getPrice()); //每期租金金额

            }

            t_contract_bill.setBasefee(t_contract.getPropertyprice());
            //t_contract_bill.setCompanyid(currentMonthDays);  //每期天数; 按天计算费用时用；
            t_contract_bill.setCompanyid(paytype); //每期月数; 按月计算费用时用；

            //应付款日期 = 本期结束日期 - 提前天数
            t_contract_bill.setPayday(DateUtil.format(DateUtil.addDay(currentEnddate, -t_contract.getPropertyprepaydays().intValue()), "yyyy-MM-dd"));
            //最后付款日期 = 本期结束日期 +7 天；
            t_contract_bill.setEndday(DateUtil.format(DateUtil.addDay(currentEnddate, 7), "yyyy-MM-dd"));

            list.add(t_contract_bill);
        }
        return list;
    }

    //计算总金额， 每月单价 *  每期月数 * 租赁递增系数；
    private String countTotalZulinPrice( Double price, int paytype,  Double rate ) {
        String totalPrice = "";
        BigDecimal brate = new BigDecimal(rate);
        BigDecimal bpaytype = new BigDecimal(paytype);
        BigDecimal bprice = new BigDecimal(price);
        totalPrice = bprice.multiply(bpaytype).multiply(brate).setScale(2, BigDecimal.ROUND_HALF_UP).toString();  //保留两位小数
        log.error("------计算总金额， 每月租金单价 * 月数（付款周期）* 租金递增系数 =" + bprice + "*" + bpaytype + "*"+brate+"=" + totalPrice);

        return totalPrice;
    }

    //计算总金额， 每月单价 * 月数；
    private String countTotalWuyePrice( Double price, int paytype ) {
        String totalPrice = "";
        BigDecimal bpaytype = new BigDecimal(paytype);
        BigDecimal bprice = new BigDecimal(price);
        totalPrice = bprice.multiply(bpaytype).setScale(2, BigDecimal.ROUND_HALF_UP).toString();  //保留两位小数
        log.error("------计算总金额， 每月物业费单价 * 月数（付款周期） =" + bprice + "*" + bpaytype + "=" + totalPrice);

        return totalPrice;
    }

    //计算总金额， 面积 * 单价 * 天数；
    private String countTotalPrice(String area, Double price, int Days) {
        String totalPrice = "";
        BigDecimal barea = new BigDecimal(area);
        BigDecimal bprice = new BigDecimal(price);
        BigDecimal bdays = new BigDecimal(Days);
        totalPrice = barea.multiply(bprice).multiply(bdays).setScale(2, BigDecimal.ROUND_HALF_UP).toString();  //保留两位小数
        log.error("------计算总金额， 面积 * 单价 * 天数=" + area + "*" + price + "*" + Days + "=" + totalPrice);

        return totalPrice;
    }

    /**
     * 6、跳转到t_contract/toT_contractList查询所有数据页面
     * return /WEB-INF/views/business/t_contract/t_contractList.jsp
     */
    @RequestMapping(value = "/toT_contractList")
    public String toT_contractList() {
        log.debug("------跳转到/WEB-INF/views/business/t_contract/t_contractList.jsp------");
        return "business/t_contract/t_contractList";
    }

    @RequestMapping(value = "/toT_contractListZulin")
    public String toT_contractListZulin() {
        log.debug("------跳转到/WEB-INF/views/business/t_contract/t_contractListZulin.jsp------");
        return "business/t_contract/t_contractListZulin";
    }

    @RequestMapping(value = "/toT_contractCurdZulin")
    public String toT_contractCurdZulin() {
        log.debug("------跳转到/WEB-INF/views/business/t_contract/t_contractCurdZulin.jsp------");
        return "business/t_contract/t_contractCurdZulin";
    }

    /**
     * 7、新增、修改、详情页面t_contract/toT_contractCurd跳转
     * business/t_contract/T_contractCurd.jsp
     */
    @RequestMapping(value = "/toT_contractCurd")
    public String toT_contractCurd() {
        log.debug("------跳转到/WEB-INF/views/business/t_contract/t_contractCurd.jsp------");
        return "business/t_contract/t_contractCurd";
    }

    /**
     * 8、批量删除T_contract根据主键id
     * 是否要实现批量删除，待考虑，基本上用途不大
     * @param id
     * @param request
     * @param response
     @RequestMapping("/delT_contractBatch") public String delT_contractBatch(HttpServletRequest request,HttpServletResponse response){
     String[] ids = request.getParameterValues("ids");
     System.out.println("------ids="+ids);
     T_contract t_contract = new T_contract();
     int j=0;
     for(int i =0;i< ids.length;i++){
     j++;
     log.error("------ids[i]="+ids[i]);
     t_contract.setContractid(new Integer(ids[i]).intValue());
     t_contractService.delete(t_contract);
     }
     if(j==ids.length){
     log.debug("------t_contract批量删除成功！------");
     }else{
     log.error("------t_contract批量删除部分成功！部分失败！------");
     }

     return "redirect:/t_contract/getAllT_contract";
     }
     */


}









